package com.sinodata.bsm.center.web.action.event;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sino.uam.entity.Department;
import com.sino.uam.entity.UserInfo;
import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.NotifyHisBean;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.bean.TreeData;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.notify.NotifyHisService;
import com.sinodata.bsm.center.user.UserUtil;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.EventConstants;
import com.sinodata.bsm.common.constants.NotifyConstants;
import com.sinodata.bsm.common.vo.Notify;

/**
 * <p>
 * Description: 通知历史查询响应Action
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-6-1 AM 10:08:25     liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class NotifyHisAction extends BaseAction<Notify> {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 6792572383758774093L;

    @Autowired
    private NotifyHisService notifyHisService;

    //private Long id;

    private String level;

    private String beginDate;

    private String endDate;

    private String mode;

    /**
     * 进入通用页面
     * 
     * @return
     */
    public String common() {
        String flag = request.getParameter("flag");
        if (flag.equals("0")) {
            String format = "yyyy-MM-dd HH:mm";
            SimpleDateFormat simple = new SimpleDateFormat(format);
            String endDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 23:59";
            String beginDate = simple.format(new Date(new Date().getTime() - 3600000 * 24 * 7));
            Struts2Utils.setRequestAttribute("beginDate", beginDate);
            Struts2Utils.setRequestAttribute("endDate", endDate);
            request.setAttribute("treeId", request.getParameter("treeId"));
            request.setAttribute("scope", request.getParameter("id"));
            request.setAttribute("flag", 0);
        } else {
            request.setAttribute("flag", 1);
            String format = "yyyyMMdd";
            SimpleDateFormat simple = new SimpleDateFormat(format);
            String time = request.getParameter("time");
            if (time.equals("1")) {
                request.setAttribute("beginDate", simple.format(new Date()));
            } else if (time.equals("2")) {
                Calendar calendar = Calendar.getInstance(Locale.CHINA);
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                request.setAttribute("beginDate", simple.format(calendar.getTime()));
            } else if (time.equals("3")) {
                Calendar calendar1 = Calendar.getInstance(Locale.CHINA);
                calendar1.add(Calendar.MONTH, -1);
                request.setAttribute("beginDate", simple.format(calendar1.getTime()).substring(0, 6) + "01");
            }
            request.setAttribute("mode", request.getParameter("mode"));
        }
        return "common";
    }

    /**
     * 显示通知信息
     * 
     * @return
     */
    public String view() {
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        NotifyHisBean notifyHisBean = notifyHisService.findById(Long.valueOf(request.getParameter("id")));
        Struts2Utils.getRequest().setAttribute("notifyHisBean", notifyHisBean);
        Struts2Utils.getRequest().setAttribute("user", (UserUtil.getInstance().getUserById(notifyHisBean.getNotifyHis().getUser()) == null ? notifyHisBean.getNotifyHis().getUser() + "(已删除)" : UserUtil.getInstance().getUserById(notifyHisBean.getNotifyHis().getUser()).getFullName()));
        Struts2Utils.getRequest().setAttribute("notify_mode", NotifyConstants.getModeDesc(notifyHisBean.getNotifyHis().getNotifyMode()));
        Struts2Utils.getRequest().setAttribute("time", simple.format(notifyHisBean.getNotifyHis().getTime()));
        Struts2Utils.getRequest().setAttribute("event_level", EventConstants.getLevelDesc(notifyHisBean.getEventLevel()));
        Struts2Utils.getRequest().setAttribute("event_occur_time", simple.format(notifyHisBean.getEventOccurTime()));
        Struts2Utils.getRequest().setAttribute("event_status", EventConstants.getStatusDesc(notifyHisBean.getEventStatus()));
        return "view";
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.ModelDriven#getModel()
     */
    @Override
    public Notify getModel() {
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#list()
     */
    @Override
    public String list() throws Exception {
        String dimension = request.getParameter("dimension");
        String resIdSearchScope = request.getParameter("resId");
        String resIdAllScope = (resIdSearchScope == null || resIdSearchScope.equals("")) ? "" : resIdSearchScope;
        //查询条件
        String level = request.getParameter("level");
        String beginDate = request.getParameter("beginDate");
        String endDate = request.getParameter("endDate");
        String eventTypeId = request.getParameter("eventTypeId");
        String mode = request.getParameter("mode");
        String userId = request.getParameter("userId");
        Condition condition = new Condition();
        Map<String, String> map = new HashMap<String, String>();
        //当前用户可见资源范围
        List<Long> authScopeList = UserFunctionValidate.getResIdListForUser(FunctionConstants.VIEW_RES);
        StringBuffer resIds = new StringBuffer();
        if (authScopeList != null && authScopeList.size() != 0) {
            for (Long resId : authScopeList) {
                resIds.append(resId).append(",");
            }
            resIds.delete(resIds.lastIndexOf(","), resIds.length());
        }
        if (resIds.toString() != null && !resIds.toString().equals("")) {
            String currentUserId = UserUtil.getInstance().getCurrentUserId();
            if (!UserUtil.getInstance().isSysAdmin(currentUserId) && !UserUtil.getInstance().isGuest(currentUserId)) {//guest用户有全部数据的查看权限
                if (resIdAllScope.equals("")) {
                    resIdAllScope = resIds.toString();
                }
            }
        } else {
            JSONObject json = new JSONObject();
            json.element("iTotalRecords", 0);
            json.element("iTotalDisplayRecords", 0);
            JSONArray array = new JSONArray();
            json.element("aaData", array);
            renderText(json.toString());
            return null;
        }
        if (level != null && !level.equals("")) {
            map.put("level_", level);
        } else {
            map.put("level_", "-1");
        }
        if (eventTypeId != null && !eventTypeId.equals("")) {
            map.put("res_type_id", eventTypeId);
        }
        if (beginDate != null && !beginDate.equals("")) {
            map.put("beginDate", beginDate);
        }
        if (endDate != null && !endDate.equals("")) {
            map.put("endDate", endDate);
        }
        if (mode != null && !mode.equals("")) {
            map.put("notify_mode", mode);
        } else {
            map.put("notify_mode", "-1");
        }
        if (userId != null && !userId.equals("")) {
            map.put("userId", userId);
        }
        //资源ID条件
        if (!resIdAllScope.equals("")) {
            map.put("resIds", resIdAllScope);
        }
        condition.setWhere(map);
        //排序
        Map<String, String> orderMap = new HashMap<String, String>();
        String order = request.getParameter("sSortDir_0");
        String col = request.getParameter("mDataProp_" + request.getParameter("iSortCol_0"));
        if (!col.equals("user")) {
            orderMap.put(col, order);
        }
        //默认按通知时间降序
        if (orderMap.isEmpty()) {
            orderMap.put("time", "desc");
        }
        Page<NotifyHisBean> page = new Page<NotifyHisBean>();
        page.setOrder(orderMap);
        page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
        page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
        Page<NotifyHisBean> aaData = notifyHisService.findByPage(page, condition, dimension);
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        JSONObject json = new JSONObject();
        json.element("iTotalRecords", page.getTotal());
        json.element("iTotalDisplayRecords", page.getTotal());
        JSONArray array = new JSONArray();
        for (NotifyHisBean notifyHisBean : aaData.getRows()) {
            JSONObject obj = new JSONObject();
            obj.element("id", notifyHisBean.getNotifyHis().getId());
            obj.element("user", (UserUtil.getInstance().getUserById(notifyHisBean.getNotifyHis().getUser()) == null ? notifyHisBean.getNotifyHis().getUser() + "(已删除)" : UserUtil.getInstance().getUserById(notifyHisBean.getNotifyHis().getUser()).getFullName()));
            obj.element("mode", notifyHisBean.getNotifyHis().getNotifyMode());
            obj.element("mode_name", "<div class='notifymode" + notifyHisBean.getNotifyHis().getNotifyMode() + "' title='" + NotifyConstants.getModeDesc(notifyHisBean.getNotifyHis().getNotifyMode()) + "'></div>");
            obj.element("time", simple.format(notifyHisBean.getNotifyHis().getTime()));
            obj.element("res_name", notifyHisBean.getResName());
            obj.element("msg", "<a href='javascript:view(" + notifyHisBean.getNotifyHis().getId() + ");'>" + notifyHisBean.getNotifyHis().getMsg() + "</a>");
            obj.element("level", notifyHisBean.getEventLevel());
            obj.element("event_level", "<div class='eventlevel" + notifyHisBean.getEventLevel() + "' title='" + EventConstants.getLevelDesc(notifyHisBean.getEventLevel()) + "'></div>");
            obj.element("status", notifyHisBean.getEventStatus());
            obj.element("event_status", "<div class='status" + notifyHisBean.getEventStatus() + "' title='" + EventConstants.getStatusDesc(notifyHisBean.getEventStatus()) + "'></div>");
            obj.element("event_time", simple.format(notifyHisBean.getEventOccurTime()));
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    public String userTreeData() {
        List<String> scopeList = new ArrayList<String>();
        String userId = request.getParameter("userId");
        if (userId != null && !userId.equals("")) {
            scopeList = Arrays.asList(userId.split(","));
        }
        Collections.sort(scopeList);
        List<TreeData> listResult = new ArrayList<TreeData>();
        Collection<Department> departmentCollection = UserUtil.getInstance().getAllDepartment();
        //获得一级组织机构
        List<Department> firstDepartmentList = new ArrayList<Department>();
        for (Department department : departmentCollection) {
            if (department.getParentId() == null && new Integer(0).equals(department.getIsDeleted())) {
                firstDepartmentList.add(department);
            }
        }
        //按序号排序
        resultSort(firstDepartmentList);
        for (Department department : firstDepartmentList) {
            TreeData treeData = new TreeData();
            treeData.setId("dept," + String.valueOf(department.getId()));
            treeData.setName(department.getName());
            treeData.setIconSkin("dept");
            listResult.add(treeData);
        }
        //未分组
        TreeData treeData = new TreeData();
        treeData.setId("dept," + "-1");
        treeData.setName("未分组");
        treeData.setIconSkin("dept");
        listResult.add(treeData);

        //遍历循环获得所有组织机构
        getUserTreeDataCycle(scopeList, listResult);
        //将用户挂到组织机构上
        getUserFromDeptCycle(scopeList, listResult);

        JSONArray jsonArray = JSONArray.fromObject(listResult);
        Struts2Utils.renderText(jsonArray.toString());
        return null;
    }

    private void getUserFromDeptCycle(List<String> scopeList, List<TreeData> listResult) {
        for (TreeData treeData : listResult) {
            if (treeData.getId().contains(",")) {
                List<TreeData> children = treeData.getChildren();
                if (children != null && children.size() != 0) {
                    getUserFromDeptCycle(scopeList, children);
                }
                if (children == null || children.size() == 0) {
                    children = new ArrayList<TreeData>();
                }
                List<UserInfo> listUserInfo = new ArrayList<UserInfo>();
                if (!(treeData.getId().split(",")[1]).equals("-1")) {
                    listUserInfo = UserUtil.getInstance().getUserByDeptId(Integer.valueOf(treeData.getId().split(",")[1]));
                } else {
                    Map<String, UserInfo> allUser = UserUtil.getInstance().getAllUsers();
                    for (String userId : allUser.keySet()) {
                        if (!userId.equals("admin") && !userId.equals("guest")) {
                            listUserInfo.add(allUser.get(userId));
                        }
                    }
                }
                for (UserInfo userInfo : listUserInfo) {
                    TreeData childrenTreeData = new TreeData();
                    childrenTreeData.setId(String.valueOf(userInfo.getId()));
                    childrenTreeData.setName(userInfo.getFullName());
                    childrenTreeData.setIconSkin("person");
                    if (Collections.binarySearch(scopeList, String.valueOf(userInfo.getId())) > -1) {
                        childrenTreeData.setChecked(true);
                    }
                    children.add(childrenTreeData);
                }
                treeData.setChildren(children);
            }

        }
    }

    private void getUserTreeDataCycle(List<String> scopeList, List<TreeData> listResult) {
        for (TreeData treeData : listResult) {
            if (treeData.getId().contains(",")) {
                List<Department> listDepartment = UserUtil.getInstance().getDepartmentListByParentId(Integer.valueOf(treeData.getId().split(",")[1]));
                //按序号排序
                resultSort(listDepartment);
                List<TreeData> childrenList = new ArrayList<TreeData>();
                for (Department department : listDepartment) {
                    TreeData treeData1 = new TreeData();
                    treeData1.setId("dept," + String.valueOf(department.getId()));
                    treeData1.setName(department.getName());
                    treeData1.setIconSkin("dept");
                    childrenList.add(treeData1);
                }
                if (childrenList.size() != 0) {
                    getUserTreeDataCycle(scopeList, childrenList);
                    treeData.setChildren(childrenList);
                }
            }
        }
    }

    private List<Department> resultSort(List<Department> sortList) {
        for (int i = 0; i < sortList.size(); i++) {
            for (int j = 0; j < sortList.size() - i - 1; j++) {
                if (sortList.get(j).getSeqNo().compareTo(sortList.get(j + 1).getSeqNo()) > 0) {
                    Department tmp = sortList.get(j);
                    sortList.set(j, sortList.get(j + 1));
                    sortList.set(j + 1, tmp);
                }
            }
        }
        return sortList;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#input()
     */
    @Override
    public String input() throws Exception {
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#save()
     */
    @Override
    public String save() throws Exception {
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#delete()
     */
    @Override
    public String delete() throws Exception {
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#prepareModel()
     */
    @Override
    protected void prepareModel() throws Exception {

    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getBeginDate() {
        return beginDate;
    }

    public void setBeginDate(String beginDate) {
        this.beginDate = beginDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public String getMode() {
        return mode;
    }

    public void setMode(String mode) {
        this.mode = mode;
    }

}